package com.hulman.oms.service;

import com.hulman.oms.bean.*;
import com.hulman.oms.dao.WaterReportDao;
import com.hulman.oms.dao.WaterReportItemDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@Service
public class WaterReportService
{
    @Autowired
    private WaterReportDao waterReportDao;
    @Autowired
    private WaterReportItemDao waterReportItemDao;
    @Autowired
    private WaterMeterService waterMeterService;

    public List<WaterReport> findWaterReports(Map<String, Object> map)
    {
        return waterReportDao.findWaterReports(map);
    }

    public Integer findWaterReportsCount(Map<String, Object> map)
    {
        return waterReportDao.findWaterReportsCount(map);
    }

    public Result findWaterReportsResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = waterReportDao.findWaterReportsCount(map);
        List<WaterReport> data = waterReportDao.findWaterReports(map);
        return new Result(data, count);
    }

    public WaterReport findWaterReportById(Integer id)
    {
        return waterReportDao.findWaterReportById(id);
    }

    public void saveWaterReport(WaterReport waterReport)
    {
        if (waterReport.getId() != null && waterReport.getId() != 0)
        {
            waterReportDao.updateWaterReport(waterReport);
        } else
        {
            waterReportDao.insertWaterReport(waterReport);
        }
    }

    public void deleteWaterReportById(Integer id)
    {
        waterReportDao.deleteWaterReportById(id);
    }

    public void deleteWaterReports(int[] ids)
    {
        waterReportDao.deleteWaterReports(ids);
    }

    @Transactional(rollbackFor = Exception.class)
    public void createReport(WaterReport report)
    {
        waterReportDao.insertWaterReport(report);
        List<WaterMeter> meters = waterMeterService.findAllWaterMeters();
        for (WaterMeter meter : meters)
        {
            WaterReportItem item = new WaterReportItem();
            item.setReportId(report.getId());
            item.setMeterId(meter.getId());
            item.setMeterName(meter.getName());
            item.setDiameter(meter.getDiameter());
            item.setRatio(meter.getRatio());
            item.setLastAmount(meter.getAmount());
            item.setState(0);
            waterReportItemDao.insertWaterReportItem(item);
        }
    }

}
